package com.yh.service.impl;

import com.yh.dao.CityMapper;
import com.yh.domain.City;
import com.yh.service.CityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author yh
 */
@Service
public class CityServiceImpl implements CityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CityServiceImpl.class);

    @Resource
    private CityMapper cityMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 根据城市id查询城市信息,假如redis中有数据,取出数据
     * 假如没有,从数据库中查询出数据,然后放入redis中
     * @param id
     * @return
     */
    @Override
    public City findCityById(Long id) {

        String key = "city:" + id;
        ValueOperations operations = redisTemplate.opsForValue();

        boolean hasKey = redisTemplate.hasKey(key);
        //假如存在
        if (hasKey) {
            City city = (City) operations.get(key);
            LOGGER.info("CityServiceImpl.findCityById() : 从缓存中获取了城市 >> " + city.toString());
            return city;
        }
        //假如redis中不存在
        City city = cityMapper.findById(id);
        operations.set(key, city, 10, TimeUnit.DAYS);
        LOGGER.info("CityServiceImpl.findCityById() : 城市插入缓存 >> " + city.toString());

        return city;
    }

    @Override
    public Long saveCity(City city) {
        return cityMapper.saveCity(city);
    }

    @Override
    public Long updateCity(City city) {
        Long ret = cityMapper.updateCity(city);

        String key = "city:" + city.getId();
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            redisTemplate.delete(key);

            LOGGER.info("CityServiceImpl.updateCity() : 从缓存中删除城市 >> " + city.toString());
        }

        return ret;
    }

    @Override
    public Long deleteCity(Long id) {

        Long ret = cityMapper.deleteCity(id);

        String key = "city:" + id;
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            redisTemplate.delete(key);

            LOGGER.info("CityServiceImpl.deleteCity() : 从缓存中删除城市 ID >> " + id);
        }
        return ret;
    }

}
